﻿using Lwk.MyLife.Core.CommonDtos;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Lwk.MyLife.Core.Helpers
{
    public class HttpClientHelper : IHttpClientHelper
    {
        private ILogger<HttpClientHelper> _logger;
        public HttpClientHelper(ILogger<HttpClientHelper> logger)
        {
            _logger = logger;
        }

        public async Task<CustomerActionResult> CustomerPostAsync(string url, string data)
        {
            var result = new CustomerActionResult();
            using (var client = new HttpClient())
            {
                try
                {
                    client.Timeout = new TimeSpan(0, 0, 10);//设置超时时长
                    var content = new StringContent(data);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    client.DefaultRequestHeaders.Connection.Add("keep-alive");
                    var response = await client.PostAsync(url, content);
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        _logger.LogError($"调用webapi接口http状态码错误：\r url:{url} \r data:{data} \r 状态码：{response.StatusCode}");
                    }
                    var responseContent = await response.Content.ReadAsStringAsync();
                    result = JsonConvert.DeserializeObject<CustomerActionResult>(responseContent);
                    return result;
                }
                catch (Exception ex)
                {
                    _logger.LogError($"访问webapi异常：\r url:{url} \r data:{data} \r 异常信息：{ex.Message}");
                    throw ex;
                }
                finally
                {
                    client.Dispose();
                }
            }
        }

        /// <summary>
        /// 通用调用webapi方法，POST
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T> PostAsync<T>(string url, string data)
        {
            var result = default(T);
            using (var client = new HttpClient())
            {
                try
                {
                    client.Timeout = new TimeSpan(0, 0, 10);//设置超时时长
                    var content = new StringContent(data);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    client.DefaultRequestHeaders.Connection.Add("keep-alive");
                    var response = await client.PostAsync(url, content);
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        _logger.LogError($"调用webapi接口http状态码错误：\r url:{url} \r data:{data} \r 状态码：{response.StatusCode}");
                    }
                    var responseContent = await response.Content.ReadAsStringAsync();
                    result = JsonConvert.DeserializeObject<T>(responseContent);
                    return result;
                }
                catch (Exception ex)
                {
                    _logger.LogError($"访问webapi异常：\r url:{url} \r data:{data} \r 异常信息：{ex.Message}");
                    throw ex;
                }
                finally
                {
                    client.Dispose();
                }
            }
        }
    }
}
